﻿using System;
using System.Collections.Generic;
using System.Text;
using Csla;
using System.Data.Odbc;
using MinaspetroLibrary.Configuracoes;
using System.Data;
using Csla.Data;

namespace MinaspetroLibrary.EnderecoPack
{
	[Serializable()]
    public class Endereco : BusinessBase<Endereco>
    {

        #region Control Properties
        [Csla.NotUndoable()]
        private bool _isEmpty = false;

        public bool IsEmpty
        {
            get { return _isEmpty; }
        }
        #endregion

        #region Business Properties and Methods

        //declare members

        private Guid _id = Guid.NewGuid();

        private string _logradouro = string.Empty;

        private string _numero = string.Empty;

        private string _complemento = string.Empty;

        private string _cep = string.Empty;

        private string _bairro = string.Empty;

        private string _uf = string.Empty;

        private string _cidade = string.Empty;


        [System.ComponentModel.DataObjectField(true, true)]
        public Guid Id
        {
            get
            {
                CanReadProperty("Id", true);
                return _id;
            }
        }

        public string Logradouro
        {
            get
            {
                CanReadProperty("Logradouro", true);
                return _logradouro;
            }
            set
            {
                CanWriteProperty("Logradouro", true);
                if (value == null) value = string.Empty;
                if (!_logradouro.Equals(value))
                {
                    _logradouro = value;
                    PropertyHasChanged("Logradouro");
                }
            }
        }

        public string Numero
        {
            get
            {
                CanReadProperty("Numero", true);
                return _numero;
            }
            set
            {
                CanWriteProperty("Numero", true);
                if (value == null) value = string.Empty;
                if (!_numero.Equals(value))
                {
                    _numero = value;
                    PropertyHasChanged("Numero");
                }
            }
        }

        public string Complemento
        {
            get
            {
                CanReadProperty("Complemento", true);
                return _complemento;
            }
            set
            {
                CanWriteProperty("Complemento", true);
                if (value == null) value = string.Empty;
                if (!_complemento.Equals(value))
                {
                    _complemento = value;
                    PropertyHasChanged("Complemento");
                }
            }
        }

        public string Cep
        {
            get
            {
                CanReadProperty("Cep", true);
                return _cep;
            }
            set
            {
                CanWriteProperty("Cep", true);
                if (value == null) value = string.Empty;
                if (!_cep.Equals(value))
                {
                    _cep = value;
                    PropertyHasChanged("Cep");
                }
            }
        }

        public string Bairro
        {
            get
            {
                CanReadProperty("Bairro", true);
                return _bairro;
            }
            set
            {
                CanWriteProperty("Bairro", true);
                if (value == null) value = string.Empty;
                if (!_bairro.Equals(value))
                {
                    _bairro = value;
                    PropertyHasChanged("Bairro");
                }
            }
        }

        public string Uf
        {
            get
            {
                CanReadProperty("Uf", true);
                return _uf;
            }
            set
            {
                CanWriteProperty("Uf", true);
                if (value == null) value = string.Empty;
                if (!_uf.Equals(value))
                {
                    _uf = value;
                    PropertyHasChanged("Uf");
                }
            }
        }

        public string Cidade
        {
            get
            {
                CanReadProperty("Cidade", true);
                return _cidade;
            }
            set
            {
                CanWriteProperty("Cidade", true);
                if (value == null) value = string.Empty;
                if (!_cidade.Equals(value))
                {
                    _cidade = value;
                    PropertyHasChanged("Cidade");
                }
            }
        }

        protected override object GetIdValue()
        {
            return _id.ToString().Trim().Replace("\"", "\\\"");
        }

        #endregion //Business Properties and Methods

        #region Validation Rules
        private void AddCustomRules()
        {
            //add custom/non-generated rules here...
        }

        private void AddCommonRules()
        {
        }

        protected override void AddBusinessRules()
        {
            AddCommonRules();
            AddCustomRules();
        }
        #endregion //Validation Rules

        #region Authorization Rules
        protected override void AddAuthorizationRules()
        {
            //TODO: Define authorization rules in Endereco
        }


        public static bool CanGetObject()
        {
            //TODO: Define CanGetObject permission in Endereco
            return true;
            //if (Csla.ApplicationContext.User.IsInRole("EnderecoViewGroup"))
            //	return true;
            //return false;
        }

        public static bool CanAddObject()
        {
            //TODO: Define CanAddObject permission in Endereco
            return true;
            //if (Csla.ApplicationContext.User.IsInRole("EnderecoAddGroup"))
            //	return true;
            //return false;
        }

        public static bool CanEditObject()
        {
            //TODO: Define CanEditObject permission in Endereco
            return true;
            //if (Csla.ApplicationContext.User.IsInRole("EnderecoEditGroup"))
            //	return true;
            //return false;
        }

        public static bool CanDeleteObject()
        {
            //TODO: Define CanDeleteObject permission in Endereco
            return true;
            //if (Csla.ApplicationContext.User.IsInRole("EnderecoDeleteGroup"))
            //	return true;
            //return false;
        }
        #endregion //Authorization Rules

        #region Factory Methods
        private Endereco()
        { /* require use of factory method */ }

        public static Endereco NewEndereco()
        {
            if (!CanAddObject())
                throw new System.Security.SecurityException("Usuário não autorizado a adicionar Endereco");
            return DataPortal.Create<Endereco>();
        }

        public static Endereco GetEndereco(Guid id)
        {
            if (!CanGetObject())
                throw new System.Security.SecurityException("Usuário não autorizado a visualizar Endereco");
            return DataPortal.Fetch<Endereco>(new Criteria(id));
        }

        public override Endereco Save()
        {
            if (IsDeleted && !CanDeleteObject())
                throw new System.Security.SecurityException("Usuário não autorizado a remover Endereco");
            else if (IsNew && !CanAddObject())
                throw new System.Security.SecurityException("Usuário não autorizado a adicionar Endereco");
            else if (!CanEditObject())
                throw new System.Security.SecurityException("Usuário não autorizado a atualizar Endereco");

            return base.Save();
        }

        public static void DeleteEndereco(Guid id)
        {
            if (!CanDeleteObject())
                throw new System.Security.SecurityException("Usuário não autorizado a remover Endereco");
            DataPortal.Delete(new Criteria(id));
        }

        #endregion //Factory Methods

        #region Data Access

        #region Criteria

        [Serializable()]
        private class Criteria
        {
            public Guid Id;

            public Criteria(Guid Id)
            {
                this.Id = Id;

            }
        }


        #endregion //Criteria

        #region Data Access - Create
        [RunLocal]
        protected override void DataPortal_Create()
        {
            _isEmpty = false;
            ValidationRules.CheckRules();
        }

        #endregion //Data Access - Create

        #region Data Access - Fetch
        private void DataPortal_Fetch(Criteria criteria)
        {
            using (OdbcConnection cn = new OdbcConnection(ConfigDatabase.MinaspetroConnection))
            {
                cn.Open();

                ExecuteFetch(cn, criteria);
            }//using

        }

        private void ExecuteFetch(OdbcConnection cn, Criteria criteria)
        {
            using (OdbcCommand cm = cn.CreateCommand())
            {
                cm.CommandType = CommandType.Text;
                cm.CommandText = GetFetchScript(criteria);

                using (SafeDataReader dr = new SafeDataReader(cm.ExecuteReader()))
                {
                    FetchObject(dr);
                    ValidationRules.CheckRules();



                    //load child object(s)
                    FetchChildren(dr);
                }
            }//using
        }

        private string GetFetchScript(Criteria criteria)
        {
            return "SELECT "
                 + "Id, "
                 + "Logradouro, "
                 + "Numero, "
                 + "Complemento, "
                 + "Cep, "
                 + "Bairro, "
                 + "Uf, "
                 + "Cidade "
                 + "FROM enderecotb "
                 + "WHERE Id=\"" + criteria.Id.ToString().Trim().Replace("\"", "\\\"") + "\";";
        }

        private void FetchObject(SafeDataReader dr)
        {
            _isEmpty = !dr.Read();
            if (_isEmpty) return;

            _id = new Guid(dr["Id"].ToString().Trim().Replace("\"", "\\\""));
            _logradouro = dr.GetString("Logradouro");
            _numero = dr.GetString("Numero");
            _complemento = dr.GetString("Complemento");
            _cep = dr.GetString("Cep");
            _bairro = dr.GetString("Bairro");
            _uf = dr.GetString("Uf");
            _cidade = dr.GetString("Cidade");
        }

        private void FetchChildren(SafeDataReader dr)
        {
        }
        #endregion //Data Access - Fetch

        #region Data Access - Insert
        protected override void DataPortal_Insert()
        {
            using (OdbcConnection cn = new OdbcConnection(ConfigDatabase.MinaspetroConnection))
            {
                cn.Open();

                ExecuteInsert(cn);

                //update child object(s)
                UpdateChildren(cn);
            }//using
            MinaspetroLibrary.UsuarioPack.Usuario.UsuarioInSession.AtualizarHitorico("Insert - Enderecotb - Id: " + _id.ToString().Trim().Replace("\"", "\\\""));
        }

        private void ExecuteInsert(OdbcConnection cn)
        {
            using (OdbcCommand cm = cn.CreateCommand())
            {
                cm.CommandType = CommandType.Text;
                cm.CommandText = GetInsertScript();

                cm.ExecuteNonQuery();
                
            }//using
        }

        private string GetInsertScript()
        {
            return "INSERT INTO enderecotb "
                +"( Id, Logradouro, Numero, Complemento, Cep, Bairro, Uf, Cidade ) "
                + " VALUES (\""
                + _id.ToString().Trim().Replace("\"", "\\\"") + "\", \""
                + _logradouro.ToString().Trim().Replace("\"", "\\\"") + "\", \""
                + _numero.ToString().Trim().Replace("\"", "\\\"") + "\", \""
                + _complemento.ToString().Trim().Replace("\"", "\\\"") + "\", \""
                + _cep.ToString().Trim().Replace("\"", "\\\"") + "\", \""
                + _bairro.ToString().Trim().Replace("\"", "\\\"") + "\", \""
                + _uf.ToString().Trim().Replace("\"", "\\\"") + "\", \""
                + _cidade.ToString().Trim().Replace("\"", "\\\"") + "\")";
        }
        #endregion //Data Access - Insert

        #region Data Access - Update
        protected override void DataPortal_Update()
        {
            using (OdbcConnection cn = new OdbcConnection(ConfigDatabase.MinaspetroConnection))
            {
                cn.Open();

                if (base.IsDirty)
                {
                    ExecuteUpdate(cn);
                }

                //update child object(s)
                UpdateChildren(cn);
            }//using
            MinaspetroLibrary.UsuarioPack.Usuario.UsuarioInSession.AtualizarHitorico("Update - Enderecotb - Id: " + _id.ToString().Trim().Replace("\"", "\\\""));
        }

        private void ExecuteUpdate(OdbcConnection cn)
        {
            using (OdbcCommand cm = cn.CreateCommand())
            {
                cm.CommandType = CommandType.Text;
                cm.CommandText = GetUpdateScript();

                if (cm.ExecuteNonQuery() == 0)
                    throw new Exception("Este registro foi editado por outro usuario.");
            }//using
        }

        private string GetUpdateScript()
        {
            return "Update enderecotb set "
                    + "Logradouro=\"" + _logradouro.ToString().Trim().Replace("\"", "\\\"") + "\", "
                    + "Numero=\"" + _numero.ToString().Trim().Replace("\"", "\\\"") + "\", "
                    + "Complemento=\"" + _complemento.ToString().Trim().Replace("\"", "\\\"") + "\", "
                    + "Cep=\"" + _cep.ToString().Trim().Replace("\"", "\\\"") + "\", "
                    + "Bairro=\"" + _bairro.ToString().Trim().Replace("\"", "\\\"") + "\", "
                    + "Uf=\"" + _uf.ToString().Trim().Replace("\"", "\\\"") + "\", "
                    + "Cidade=\"" + _cidade.ToString().Trim().Replace("\"", "\\\"") + "\" "
                                   
                    + "WHERE Id=\"" + _id.ToString().Trim().Replace("\"", "\\\"") + "\";";
        }

        private void UpdateChildren(OdbcConnection cn)
        {
        }
        #endregion //Data Access - Update

        #region Data Access - Delete
        protected override void DataPortal_DeleteSelf()
        {
            DataPortal_Delete(new Criteria(_id));
        }

        private void DataPortal_Delete(Criteria criteria)
        {
            using (OdbcConnection cn = new OdbcConnection(ConfigDatabase.MinaspetroConnection))
            {
                cn.Open();

                ExecuteDelete(cn, criteria);

            }//using
            MinaspetroLibrary.UsuarioPack.Usuario.UsuarioInSession.AtualizarHitorico("Delete - Enderecotb - Id: " + _id.ToString().Trim().Replace("\"", "\\\""));
        }

        private void ExecuteDelete(OdbcConnection cn, Criteria criteria)
        {
            using (OdbcCommand cm = cn.CreateCommand())
            {
                cm.CommandType = CommandType.Text;
                cm.CommandText = cm.CommandText = "DELETE from enderecotb WHERE Id=\"" + criteria.Id.ToString().Trim().Replace("\"", "\\\"") + "\";";

                cm.ExecuteNonQuery();
            }//using
        }
        #endregion //Data Access - Delete
        #endregion //Data Access
    }
}